<template>
  <div class="fee-container">
    <el-button
        type="warning"
        icon="el-icon-arrow-left"
        @click="goBack"
        style="margin-bottom: 20px;"
    >
      返回缴费
    </el-button>

    <!-- 余额展示 -->
    <el-card class="balance-card" shadow="hover">
      <div class="balance-item">
        <div class="balance-label">水费余额</div>
        <div class="balance-value">¥ {{ waterBalance }}</div>
      </div>
      <div class="balance-item">
        <div class="balance-label">电费余额</div>
        <div class="balance-value">¥ {{ electricityBalance }}</div>
      </div>
      <div class="balance-item">
        <div class="balance-label">燃气余额</div>
        <div class="balance-value">¥ {{ gasBalance }}</div>
      </div>
    </el-card>

    <!-- 数据可视化部分 -->
    <div class="dashboard">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="chart-container">
            <div class="chart-title">近30日用量趋势</div>
            <div ref="lineChart" style="height: 400px;"></div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="chart-container">
            <div class="chart-title">费用类型分布</div>
            <div ref="pieChart" style="height: 400px;"></div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 费用列表 -->
    <div class="fee-list">
      <div class="list-header">费用记录</div>
      <el-table :data="feeList" border style="width: 100%">
        <el-table-column prop="createTime" label="账单日期" width="300"></el-table-column>
        <el-table-column prop="type" label="费用类型" width="240">
          <template #default="scope">
            <el-tag :type="getTagType(scope.row.type)">
              {{ getTypeName(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="consumed" label="消耗量" width="200">
          <template #default="scope">
            {{ scope.row.consumed }} {{ getUnit(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="200">
          <template #default="scope">
            ¥ {{ scope.row.amount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="200">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'warning' : 'danger'">
              {{ scope.row.status === 1 ? '已支付' : '待支付' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
          background
          :current-page="pagination.current"
          :page-size="pagination.size"
          :total="pagination.total"
          layout="total, prev, pager, next"
          @current-change="handlePageChange"
          style="margin-top: 20px;"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import {get, post} from '@/plugins/axios';
import * as echarts from 'echarts';
import {getCookieForObject} from "@/util";
import { useRouter } from 'vue-router';

export default {
  setup() {
    const router = useRouter();
    const waterBalance = ref(0);
    const electricityBalance = ref(0);
    const gasBalance = ref(0);

    const feeList = ref([]);
    const lineChart = ref(null);
    const pieChart = ref(null);

    const pagination = reactive({
      current: 1,
      size: 10,
      total: 0
    });

    // 获取用户余额
    const fetchUserBalance = () => {
      const user = getCookieForObject('user');
      waterBalance.value = user.water;
      electricityBalance.value = user.electricity;
      gasBalance.value = user.gas || 0;
    };

    // 返回缴费页面
    const goBack = () => {
      router.go(-1);
    };

    // 获取费用列表
    const fetchFeeList = async () => {
      const userId = getUserId();
      get('/fee/list',{
        pageNo: pagination.current,
        pageSize: pagination.size,
        userId: userId
      }, content => {
        feeList.value = content.records;
        pagination.total = content.total;
      })
    };

    // 获取图表数据
    const fetchChartData = () => {
      const userId = getUserId();
      get('/fee/dailyConsumption',{userId:userId},content=>{
        initLineChart(content);
      })
      get('/fee/feeDistribution',{userId:userId},content=>{
        initPieChart(content);
      })
    };

    // 初始化折线图
    const initLineChart = (data) => {
      if (!lineChart.value) return;
      const chart = echarts.init(lineChart.value);

      // 处理数据 - 按类型分组
      const waterData = [];
      const electricData = [];
      const gasData = [];
      const dates = [];

      data.forEach(item => {
        const date = item.date;
        if (!dates.includes(date)) {
          dates.push(date);
        }

        if (item.type === 1) {
          waterData.push({
            date,
            value: item.total_consumed
          });
        } else if (item.type === 2) {
          electricData.push({
            date,
            value: item.total_consumed
          });
        } else if (item.type === 3) {
          gasData.push({
            date,
            value: item.total_consumed
          });
        }
      });

      // 填充数据
      const waterValues = dates.map(date => {
        const item = waterData.find(d => d.date === date);
        return item ? item.value : 0;
      });

      const electricValues = dates.map(date => {
        const item = electricData.find(d => d.date === date);
        return item ? item.value : 0;
      });

      const gasValues = dates.map(date => {
        const item = gasData.find(d => d.date === date);
        return item ? item.value : 0;
      });

      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            let result = params[0].name + '<br/>';
            params.forEach(item => {
              result += `${item.seriesName}: ${item.value} ${getUnit(item.seriesIndex + 1)}<br/>`;
            });
            return result;
          }
        },
        legend: {
          data: ['水用量', '电用量', '燃气用量']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates
        },
        yAxis: {
          type: 'value',
          name: '用量'
        },
        series: [
          {
            name: '水用量',
            type: 'line',
            smooth: true,
            data: waterValues,
            lineStyle: {
              color: '#1890ff'
            }
          },
          {
            name: '电用量',
            type: 'line',
            smooth: true,
            data: electricValues,
            lineStyle: {
              color: '#faad14'
            }
          },
          {
            name: '燃气用量',
            type: 'line',
            smooth: true,
            data: gasValues,
            lineStyle: {
              color: '#52c41a'
            }
          }
        ]
      };

      chart.setOption(option);
      window.addEventListener('resize', () => chart.resize());
    };

    // 初始化扇形图
    const initPieChart = (data) => {
      if (!pieChart.value) return;
      const chart = echarts.init(pieChart.value);

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: ¥{c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: data.map(item => {
            if (item.type === 1) return '水费';
            if (item.type === 2) return '电费';
            if (item.type === 3) return '燃气费';
            return '其他';
          })
        },
        series: [
          {
            name: '费用分布',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: data.map(item => ({
              value: item.total_amount,
              name: item.type === 1 ? '水费' :
                  item.type === 2 ? '电费' :
                      item.type === 3 ? '燃气费' : '其他'
            }))
          }
        ]
      };

      chart.setOption(option);
      window.addEventListener('resize', () => chart.resize());
    };

    // 处理分页变化
    const handlePageChange = (page) => {
      pagination.current = page;
      fetchFeeList();
    };

    // 获取类型名称
    const getTypeName = (type) => {
      switch (type) {
        case 1: return '水费';
        case 2: return '电费';
        case 3: return '燃气费';
        default: return '其他';
      }
    };

    // 获取单位
    const getUnit = (type) => {
      switch (type) {
        case 1: return '吨';
        case 2: return '度';
        case 3: return '立方米';
        default: return '';
      }
    };

    // 获取标签类型
    const getTagType = (type) => {
      switch (type) {
        case 1: return 'primary';
        case 2: return 'warning';
        case 3: return 'success';
        default: return 'info';
      }
    };

    // 获取用户ID
    const getUserId = () => {
      const userinfo = getCookieForObject('user');
      return userinfo.id;
    };

    onMounted(() => {
      fetchUserBalance();
      fetchFeeList();
      setTimeout(() => {
        fetchChartData();
      }, 500);
    });

    return {
      waterBalance,
      electricityBalance,
      gasBalance,
      feeList,
      lineChart,
      pieChart,
      pagination,
      handlePageChange,
      getTypeName,
      getTagType,
      getUnit,
      goBack
    };
  }
};
</script>

<style scoped>
.fee-container {
  padding: 20px;
}

.balance-card {
  margin-bottom: 20px;
  background: linear-gradient(135deg, #f5f7fa, #e4edf9);
  border-radius: 8px;
  overflow: hidden;
}

.balance-item {
  display: inline-block;
  padding: 20px 40px;
  text-align: center;
  border-right: 1px solid #ebeef5;
}

.balance-item:last-child {
  border-right: none;
}

.balance-label {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.balance-value {
  font-size: 24px;
  font-weight: bold;
  color: #ff7940;
}

.dashboard {
  margin-bottom: 20px;
}

.chart-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
  height: 500px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.fee-list {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.list-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}
</style>